package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.CrmStudent;
import com.ruoyi.system.domain.CrmStudentVo;
import com.ruoyi.system.mapper.CrmStudentMapper;
import com.ruoyi.system.service.ICrmStudentService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWorkWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 学员信息Service业务层处理
 * 
 * @author Bill
 * @date 2024-06-22
 */
@Service
public class CrmStudentServiceImpl implements ICrmStudentService 
{
    @Autowired
    private CrmStudentMapper crmStudentMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWorkWeixinService workWeixinService;

    /**
     * 查询学员信息
     * 
     * @param id 学员信息主键
     * @return 学员信息
     */
    @Override
    public CrmStudent selectCrmStudentById(Long id)
    {
        return crmStudentMapper.selectCrmStudentById(id);
    }

    @Override
    public CrmStudentVo selectCrmStudentVoById(Long id) {

        CrmStudent student = selectCrmStudentById(id);

        CrmStudentVo studentVo = new CrmStudentVo();
        BeanUtils.copyBeanProp(studentVo, student);
        if(student.getResourceUserId() != null && student.getResourceUserId() != 0) {
            studentVo.setResourceUser(userService.selectUserById(student.getResourceUserId()).getUserName());
        }

        if(student.getSalesmanId() != null && student.getSalesmanId() != 0) {
            studentVo.setSalesman(userService.selectUserById(student.getSalesmanId()).getUserName());
        }
        return studentVo;
    }

    /**
     * 查询学员信息列表
     * 
     * @param crmStudent 学员信息
     * @return 学员信息
     */
    @Override
    public List<CrmStudent> selectCrmStudentList(CrmStudent crmStudent)
    {
        return crmStudentMapper.selectCrmStudentList(crmStudent);
    }

    @Override
    public void selectCrmStudentVoList(TableDataInfo rspData) {


        List<CrmStudent> students = (List<CrmStudent>) rspData.getRows();
        List<CrmStudentVo> studentVos = Collections.EMPTY_LIST;

        if(!CollectionUtils.isEmpty(students)) {
            studentVos = new ArrayList<>(students.size());
            for (int i = 0; i < students.size(); i++) {
                CrmStudent student = students.get(i);
                CrmStudentVo studentVo = new CrmStudentVo();
                BeanUtils.copyBeanProp(studentVo, student);
                if(student.getResourceUserId() != null && student.getResourceUserId() != 0) {
                    studentVo.setResourceUser(userService.selectUserById(student.getResourceUserId()).getUserName());
                }

                if(student.getSalesmanId() != null && student.getSalesmanId() != 0) {
                    studentVo.setSalesman(userService.selectUserById(student.getSalesmanId()).getUserName());
                }

                studentVos.add(studentVo);
            }
        }

        rspData.setRows(studentVos);
    }

    /**
     * 新增学员信息
     * 
     * @param crmStudent 学员信息
     * @return 结果
     */
    @Override
    public int insertCrmStudent(CrmStudent crmStudent)
    {

        if(crmStudent.getSalesmanId() == null) {
            SysUser queryUser = new SysUser();
            queryUser.setSaleStatus("0");

            List<SysUser> users = userService.selectSalesmanList(queryUser);

            // TODO: 2024/6/28 移除企业微信账号不存在的用户

            if (!CollectionUtils.isEmpty(users)) {
                Random random = new Random();
                int index = random.nextInt(users.size());

                SysUser user = users.get(index);
                crmStudent.setSalesmanId(user.getUserId());
            }
        }

        try {
            if(crmStudent.getSalesmanId() != null) {
                workWeixinService.sendStudentMessage(crmStudent);
                crmStudent.setAllocationTime(DateUtils.getNowDate());
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        crmStudent.setCreateTime(DateUtils.getNowDate());
        return crmStudentMapper.insertCrmStudent(crmStudent);
    }

    /**
     * 修改学员信息
     * 
     * @param crmStudent 学员信息
     * @return 结果
     */
    @Override
    public int updateCrmStudent(CrmStudent crmStudent)
    {
        CrmStudent oldStu = selectCrmStudentById(crmStudent.getId());

        if(crmStudent.getSalesmanId() != null) {

            if (oldStu.getSalesmanId() == null || oldStu.getSalesmanId().longValue() != crmStudent.getSalesmanId().longValue()) {
                try {
                    workWeixinService.sendStudentMessage(crmStudent);
                    crmStudent.setAllocationTime(DateUtils.getNowDate());
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        crmStudent.setUpdateTime(DateUtils.getNowDate());
        return crmStudentMapper.updateCrmStudent(crmStudent);
    }

    /**
     * 批量删除学员信息
     * 
     * @param ids 需要删除的学员信息主键
     * @return 结果
     */
    @Override
    public int deleteCrmStudentByIds(String ids)
    {
        return crmStudentMapper.deleteCrmStudentByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除学员信息信息
     * 
     * @param id 学员信息主键
     * @return 结果
     */
    @Override
    public int deleteCrmStudentById(Long id)
    {
        return crmStudentMapper.deleteCrmStudentById(id);
    }

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userService.selectUserList(user);
    }

    @Override
    public List<SysUser> selectSalesmanList(SysUser user, Long... salesmanIds) {

        List<SysUser> users = userService.selectSalesmanList(user);

        return getUsersIncludeById(users, salesmanIds);
    }

    @Override
    public List<SysUser> selectPromotionList(SysUser user, Long... promotionIds) {

        List<SysUser> users = userService.selectPromotionList(user);

        return getUsersIncludeById(users, promotionIds);
    }

    @Override
    public int changeFollowStatus(CrmStudent student) {

        CrmStudent oldStudent = selectCrmStudentById(student.getId());

        student.setSalesmanId(oldStudent.getSalesmanId());
        return crmStudentMapper.updateCrmStudent(student);
    }

    @Override
    public int changeCollectStatus(CrmStudent student) {
        CrmStudent oldStudent = selectCrmStudentById(student.getId());

        student.setSalesmanId(oldStudent.getSalesmanId());
        return crmStudentMapper.updateCrmStudent(student);
    }

    /**
     * 查询用户并包含必须用户
     * @param userIds 必须包含的用户IDS
     * @param users 用户列表
     * @return
     */
    private List<SysUser> getUsersIncludeById(List<SysUser> users, Long... userIds) {

        if(!CollectionUtils.isEmpty(Arrays.asList(userIds))) {
            if(CollectionUtils.isEmpty(users)) {
                users = new ArrayList<>(users.size());
            }

            for (int i = 0; i < userIds.length; i++) {
                SysUser user = userService.selectUserById(userIds[i]);
                if(user != null) {
                    users.add(user);
                }
            }

            if(!CollectionUtils.isEmpty(users)) {
                // 使用Stream API去重，基于id属性
                List<SysUser> uniqueUsers = users.stream()
                        .collect(Collectors.toMap(
                                SysUser::getUserId, // 使用ID作为Map的键
                                Function.identity(), // 映射的值就是元素本身
                                (existing, replacement) -> existing // 如果键冲突，保留现有的
                        )).values().stream() // 获取Map的value集合，即去重后的元素集合
                        .collect(Collectors.toList()); // 将Stream收集回List
                users = uniqueUsers;
            }
        }
        return users;
    }
}
